import cgi
import os

from google.appengine.ext.webapp import template
from google.appengine.api import datastore
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from django.utils import simplejson

from rpc_methods import RPCMethods
import datamodel
import tvdb
import tvweb

class MainPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            current_user = user.nickname()
            data = self.load_data()
            template_values = {
                'current_user': current_user,
                'logout_url': users.create_logout_url(self.request.uri),
                'series': data.get('series', []),
                'today': data.get('today', []),
                'notify': data.get('notify', ' '),
                'direct': data.get('direct', None),
                'theme': data.get('theme', 'dark-hive'),
                'layout': data.get('layout', 'layout.css')
            }
            
            path = os.path.join(os.path.dirname(__file__), "templates/index.html")
            self.response.out.write(template.render(path, template_values))
        else:
            self.redirect(users.create_login_url(self.request.uri))
            
    def load_data(self):
        data = {}
        try:
            data['series'] = tvdb.restore_series(users.get_current_user())
        except:
            pass
        try:
            data['today'] = tvdb.search_today_episodes(users.get_current_user())
        except:
            pass
        try:
            pref = tvdb.load_preferences(users.get_current_user())
            if pref[0].notify:
                data['notify'] = 'checked'
            if pref[0].direct:
                data['direct'] = 'checked'
        except:
            pass
        try:
            design = tvdb.load_design(users.get_current_user())
            if design.count() > 0:
                data['layout'] = design[0].layout
                data['theme'] = design[0].theme
        except:
            pass
        return data
        
        
class Design(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            current_user = user.nickname()
            template_values = {
                'current_user': current_user
            }
            
            path = os.path.join(os.path.dirname(__file__), "templates/theme.html")
            self.response.out.write(template.render(path, template_values))
        else:
            self.redirect(users.create_login_url(self.request.uri))
        
        
class RPCHandler(webapp.RequestHandler):
    
    def __init__(self):
        webapp.RequestHandler.__init__(self)
        self.methods = RPCMethods()
        
    def get(self):
        func = None
        
        action = self.request.get('action')
        if action:
            if action[0] == '_':
                self.error(403) # access denied
                return
            else:
                func = getattr(self.methods, action, None)
                
        if not func:
            self.error(404) # file not found
            return
            
        args = ()
        while True:
            key = 'arg%d' % len(args)
            val = self.request.get(key)
            if val:
                args += (simplejson.loads(val),)
            else:
                break
        result = func(*args)
        self.response.out.write(simplejson.dumps(result))
        
    def post(self):
        args = simplejson.loads(self.request.body)
        func, args = args[0], args[1:]
       
        if func[0] == '_':
            self.error(403) # access denied
            return
         
        func = getattr(self.methods, func, None)
        if not func:
            self.error(404) # file not found
            return

        result = func(*args)
        self.response.out.write(simplejson.dumps(result))
        

def main():
    application = webapp.WSGIApplication([
        ('/', MainPage),
        ('/rpc', RPCHandler),
        ('/design', Design)
        ], debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
